var ThumbnailLazyLoad = {
  thumbnails: [],
  updating: false,
  body: null,

  init: function() {
    var thumbnails = [];

    // collect all thumbnails into a static array arranged by
    // each element's cumulative offset from the top of the page
    // grouped into buckets of 100px
    $$('.thumbnail').each(function(img, i) {
      var src = img.src;
      img.src = '';
      img.id = 'lazy-load-' + i;

      thumbnails.push({
        id: img.id,
        src: src
      });
    });
    ThumbnailLazyLoad.thumbnails = thumbnails;

    Event.observe(window, 'scroll', ThumbnailLazyLoad.updateViewport);
    Event.observe(window, 'resize', ThumbnailLazyLoad.updateViewport);
    ThumbnailLazyLoad.updateViewport();
  },

  updateViewport: function() {
    if (ThumbnailLazyLoad.updating) return;
    ThumbnailLazyLoad.updating = true;

    var top = document.viewport.getScrollOffsets();
    top = top.top + document.viewport.getHeight();

    var thumbnails = $A(ThumbnailLazyLoad.thumbnails);
    thumbnails = thumbnails.select(function(info) {
      var img = $(info.id);
      if (img) {
        var offset = img.cumulativeOffset();

        if (top >= offset.top - 20) {
          img.src = info.src;
          return false;
        }
      }

      // retain
      return true;
    });

    if (thumbnails.length == 0) {
      // we've shown all thumbnails, kill this event handler
      Event.stopObserving(window, 'scroll', ThumbnailLazyLoad.updateViewport);
      Event.stopObserving(window, 'resize', ThumbnailLazyLoad.updateViewport);
    }

    ThumbnailLazyLoad.thumbnails = thumbnails;
    ThumbnailLazyLoad.updating = false;
  }
};
document.observe('dom:loaded', ThumbnailLazyLoad.init);
